<?php
namespace app\wchat\controller;

use think\Controller;
use think\Db;

class Wxsdk extends  Controller
{
    protected $appid,$appsecret,$access_token,$access_token_time,$ticket,$ticket_time,$shop_id;

	/**
     * 构造方法
     */
    public function __construct($shop_id=0)
    {
        // 验证店铺参数是否完整
        if($shop_id == 0){
            die("店铺参数缺失");
        }

        // 查询用户信息
        $shop_info = Db("shops")->field("appid,appsecret,access_token,access_token_time,ticket,ticket_time")->where('shop_id',$shop_id)->find();
        if(!$shop_info){
            die("未查到该商户信息");
        }

        // 店铺id
        $this->shop_id          = $shop_id;

        // 微信配置信息赋值
        $this->appid            = $shop_info['appid'];
        $this->appsecret        = $shop_info['appsecret'];

        // sdk配置信息
        $this->access_token     = $shop_info['access_token'];
        $this->access_token_time= $shop_info['access_token_time'];
        $this->ticket           = $shop_info['ticket'];
        $this->ticket_time      = $shop_info['ticket_time'];

    }


    /**
     * 获取access_token
     */
    public function getAccessToken()
    {
        // 初始化变量
        $token = '';

        // 验证已有的access_token是否本地失效
        if($this->access_token && $this->access_token_time > time()){

            $token = $this->access_token;

        } else {

            // 获取新的access_token
            $url    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
            $res    = $this->https_request($url);
            $res    = json_decode($res,true);

            if($res['access_token']){

                $data['access_token']       = $res['access_token'];
                $data['access_token_time']  = time() + 7000;

                // 更新数据库
                Db("shops")->where('shop_id',$this->shop_id)->update($data);

                $token = $res['access_token'];
            }
        }

        return $token;
    }


    /**
     * 获取ticket
     */
    public function getTicket()
    {
        // 获取access_token
        $this->access_token = $this->getAccessToken();
        if (!$this->access_token) {
            echo 'access_token error';
            die;
        }

        $jsapi_ticket = '';

        if($this->ticket && $this->ticket_time > time()){

            $jsapi_ticket = $this->ticket;

        } else {

            $url    = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$this->access_token&type=jsapi";
            $res    = $this->https_request($url);
            $res    = json_decode($res,true);

            if($res['errmsg'] == 0){

                $data['ticket']     = $res['ticket'];
                $data['ticket_time']= time() + 7000;

                // 更新数据库
                Db("shops")->where('shop_id',$this->shop_id)->update($data);

                $ticket = $res['ticket'];
            }
        }

        return $ticket;
    }


    /**
     * 发送模板消息
     * $openid              接收者openid       oTJius6kQ2hFOF66Dw0l5Xg-ICUM
     * $template_id         模板ID             BWrP-c1uXNvLvO-YNDtbVGVd0iiP7O3LibkzXkHirTI
     * $url                 详情跳转地址        http://www.qq.com
     * $data_arr            数据体             数组
     */
    public function sentMsg($openid, $template_id , $url = '' , $data_arr=[])
    {
        // 获取access_token
        $access_token = $this->getAccessToken();

        // 接口地址
        $api = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        // 模板参数
        $data['touser']         = $openid;
        $data['template_id']    = $template_id;
        $data['url']            = $url;

        // 模板数据
        $data['data']           = $data_arr;

        // 转json类型
        $data = json_encode($data);

        // 发送消息
        $res = $this->https_request($api, $data);
        $res = json_decode($res, true);

        return $res;
    }


    /**
     * 获取微信sdk配置信息
     */
    public function js_config($url)
    {
        // 获取ticket
        $jsapi_ticket = $this->getTicket();
        if (!$jsapi_ticket) {
            echo 'ticket error';
            die;
        }

        $noncestr   = "Wm3WZYTPz0wz" . rand(0000, 9999);
        $timestamp  = time();
        $sha1_str   = "jsapi_ticket={$jsapi_ticket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
        $signature  = sha1($sha1_str);

        $config['timestamp']    = $timestamp;
        $config['noncestr']     = $noncestr;
        $config['signature']    = $signature;
        $config['appId']        = $this->appid;

        return $config;
    }


    /**
     * https请求
     */
    public function https_request($url, $data = null)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($curl);

        curl_close($curl);

        return $output;
    }

}
